import {
    API
} from "../../utils/fireapi";
Component({
    /**
     * 组件的属性列表
     */
    options:{
        addGlobalClass:true
    },
    properties: {
        bgColors: {
            type: Array
        },
        image:{
            type:String,
            value:""
        },
        // 水印图片
        waterPic:{
            type:String,
            value:""
        },
        waterText:{
            type:String,
            value:""
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        selected: 0,
        canvas: undefined,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 更换背景色
        changeBg(event) {
            
            let index = (event == 0) ? 0 : event.target.dataset.index;
            this.setData({
                selected: index
            })
            if(this.data.image && this.data.bgColors.length >0){
                // 从缓存中取出去掉背景的图像
                let canvas = this.data.canvas;
                let segmentImg = this.data.image;
                let bgPrimaryColor = this.data.bgColors[index].primary_color;
                let bgSecondColor = this.data.bgColors[index].secondary_color == '#000000'?this.data.bgColors[index].primary_color:this.data.bgColors[index].secondary_color;
                
                API.drawBackground(canvas, segmentImg, bgPrimaryColor, bgSecondColor).then((res) => {
                    this.urlChange(res);
                });

            }
        },
        urlChange(url){
            let imgBase64 = this.data.canvas.toBase64();
            let bg = this.data.selected;
            // 如果传入了水印图片怎增加水印
            let waterPic = this.data.waterPic;
            let waterText = this.data.waterText;
            if (waterPic !== "" || waterText !== ""){
                let canvas = this.data.canvas;
                API.drawWater(canvas,url,waterPic,waterText).then(res=>{
                    this.triggerEvent('changed', {url:res,img:imgBase64,bg:bg});
                })

            }else{
                this.triggerEvent('changed', {url:url,img:imgBase64,bg:bg});
            }
        }
    },
    lifetimes: {

        /**初始化动作 */
        attached() {
            this.setData({
                canvas: this.selectComponent("#canvas-background")
            })

        },
        ready(){
            if(this.data.image){
                this.changeBg(this.data.selected);
            }
        }
    },
    observers: {
        'bgColors': function (bgColors) {
            if(bgColors.length>0){
                this.changeBg(0);
            }
        },
        'image':function(img){
            if(img){
                this.changeBg(this.data.selected);
            }
        }
    }
})